<?php

/**
 * Description of ConnexionController
 *
 * @author FFOZEU
 */
namespace Applications\Modules\Users\Frontend\Controller;

use Library\BackController;
use Library\HttpRequest;
use Library\Classe\Form\Form;
use Library\User;
use Applications\Modules\Users\Models\Users;

class UsersController extends BackController{
    
    public function executeConnect(HttpRequest $request)
    {
        $this->page->addVar('title', 'login');
        $loginError = '';
        $loginForm = new Form('login','post');
       
        $loginForm->action('login.html');
        
        $loginForm->add('Text', 'pseudo')
                   ->label('Pseudo')
                   ->required(true);
        
        $loginForm->add('Password', 'password')
                   ->label('Mot de passe')
                   ->required(true);
        
        $loginForm->add('Submit', 'submit')->value('Valider');
        //var_dump($_POST);
        if($request->getMethod('post')){
           //test de la validation du post
            if ($loginForm->is_valid($_POST)) {
                
                list($pseudo, $mdp) = $loginForm->get_cleaned_data('pseudo','password');
                
                $manager = $this->managers->getManagerOf('Users');
        
                $user = $manager->verifLogin($pseudo, $mdp);
                if(empty ($user)){
                    $loginError ='les paramètres saisies sont incorrectes ou votres compte n\'est pas activé';
                    $loginForm->bound($_POST);
                }else{
                    $this->logIn($user);
                    $this->app->httpResponse()->redirect('index.html');
                }
            }else{
                // 
                $loginForm->bound($_POST);
            }
        }else{
            $loginForm->bound($_POST);
        }
        $this->page->addVar('loginError', $loginError);
        $this->page->addVar('loginForm', $loginForm);
        
    }
    public function executeConnect2(HttpRequest $request)
    {
        if($request->getMethod('post')){
            
            $manager = $this->managers->getManagerOf('Users');
            $pseudo = $request->postData('id_pseudo');
            $mdp = $request->postData('id_password');
            $user = $manager->verifLogin($pseudo, $mdp);
            if(empty ($user)){
                $loginError ='les paramètres saisies sont incorrectes ou votres compte n\'est pas activé';
                $this->app->httpResponse()->redirect('login.html');
            }else{
                $this->logIn($user);
                $this->app->httpResponse()->redirect('index.html');
            }
        }else{
            $this->app->httpResponse()->redirect('login.html');
        }
           //test de la validation du post
    }
    public function executeCreate(HttpRequest $request)
    {
        $this->page->addVar('title', 'create account');
        $registerError = '';
        $registerForm = new Form('register','post');
        
        $registerForm->action('create-user.html');
                
        $registerForm->add('Text', 'pseudo')
                     ->label('Pseudo')
                     ->required(true);
        
        $registerForm->add('Password', 'password')
                     ->label('Mot de passe')
                     ->required(true);
        
        $registerForm->add('Password', 'verif_mdp')
                     ->label('Mot de passe(confirmation)')
                     ->required(true);
        
        $registerForm->add('Email', 'email')
                     ->label('E-mail')
                     ->required(true);
        
        $registerForm->add('Captcha', 'captcha')
                     ->label('Captcha')
                     ->required(true);
        
        $registerForm->add('Checkbox', 'newsletter')
                     ->label('J\'accepte de recevoir des mails de la part de Kristoclic')
                     ->required(FALSE);
        
        $registerForm->add('Checkbox', 'cgv')
                     ->label("J'ai lu et j'accepte les conditions générales")
                     ->required(true);
        
        $registerForm->add('Submit', 'submit')->value("S'inscrire");
         //* ajout de la variable à la page
        if($request->getMethod('post')){
           //test de la validation du post
            if ($registerForm->is_valid($_POST) && $_POST['password']==$_POST['verif_mdp']) {
                
                list($pseudo, $password,$verif_mdp,$email,$captcha,$news) = $registerForm->get_cleaned_data('pseudo','password','verif_mdp','email','captcha','newsletter');
                $news = isset($news)?1:0;
                $manager = $this->managers->getManagerOf('Users');
        
                $user = $manager->verifInscription($pseudo, $email);
                
                $ipProt1 = $request->resquestIp().':'.$request->resquestPort();
                
                $ipProt = $manager->verifIpPort($ipProt1);
                if(!empty ($user)){
                    $registerError ='Ce pseudo ou E-mail est déjà utilisé';
                    $registerForm->bound($_POST);
                }else{
                    if(!empty ($ipProt)){
                        $registerError ="Un compte a été déjà créé aujourd'hui depuis votre machine";
                        $registerForm->bound($_POST);
                    }else{
                       if($manager->addUser($pseudo,$email,$password,$ipProt1,$news)){
                           $this->sendMail($email, $pseudo);
                           $this->LogIn($manager->verifLogin($pseudo, $password));;
                           $this->app->httpResponse()->redirect('/');
                       }else{
                           $registerError ="Echec lors de l'inscriptions";
                           $registerForm->bound($_POST);
                       }
                        
                    }
                }
            }else{
                $registerError ="Vérifier les données saisies";
                $registerForm->bound($_POST);
            }
        }else{
            $registerForm->bound($_POST);
        }
        $this->page->addVar('registerError', $registerError);
        $this->page->addVar('registerForm', $registerForm);
    }
    
    //mise à jour des données de l'utilisateur
    public function executeUpdate(HttpRequest $request)
    {
        $registerError = '';
        $user = new User($this->app);
        //on texte si l'utilisateur est bien identifié
        if(!$user->isAuthenticated()){
            $this->app->httpResponse()->redirect('login.html');
        }
        $manager = $this->managers->getManagerOf('Users');
        $paramUser =  $manager->findUserById(intval($user->getId()));
        $registerForm = new Form('updateuser','post');
        $registerForm->action('update-user'.$request->getData('id').'.html');
        
        $registerForm->add('Select', 'civilite')
                     ->label('Civilité')
                     ->choices(array(
                        '' => '--- Votre Civilité ---',
                        'M.' => 'M.',
                        'Mme' => 'Mme',
                        'Mlle' => 'Mlle'
                     ))
                     ->required(true);
        
        $registerForm->add('Text', 'email')
                     ->label('Email')
                     ->required(true);
        
        $registerForm->add('Text', 'nom')
                     ->label('Nom')
                     ->required(true);
        
        $registerForm->add('Text', 'prenom')
                     ->label('Prénom')
                     ->required(true);
        
        $registerForm->add('Textarea', 'adresse')
                     ->label('Adresse')
                     ->required(true);
        
        $registerForm->add('Text', 'cp')
                     ->label('Cp')
                     ->required(true);
        
        $registerForm->add('Text', 'fixe')
                     ->label('Télephone fixe')
                     ->required(true);
         
        $registerForm->add('Text', 'portable')
                     ->label('Téléphone mobile')
                     ->required(false);
        
        $registerForm->add('Text', 'ville')
                     ->label('Ville')
                     ->required(false);
          
        $paysmanager = $this->managers->getManagerOf('Pays');
        $listePays = $paysmanager->getListePays();
        $output=array();
        foreach ($listePays as $key => $value) {
              $output[$value->getId()]=utf8_encode($value->getPays());             
        }
        $registerForm->add('Select', 'pays')
                     ->label('Pays')
                     ->choices($output)
                     ->required(true);
        $registerForm->add('Hidden', 'id')->value($request->getData('id'));
        $registerForm->add('Submit', 'submit')->value("Modifier");
         //* ajout de la variable à la page
        if($request->getMethod('post')){
           //test de la validation du post
            if ($registerForm->is_valid($_POST)) {
                $updteuser = new Users($_POST);
                if($manager->updateUser($updteuser)){
                    $useArray[]=$updteuser;
                    $registerError = 'Mise à jour effectuée avec succès.';
                    //$this->logIn($useArray);
                    $this->app->httpResponse()->redirect('/');
                }
            }else{
                // 
                $registerForm->bound($_POST);
            }
        }else{
            $registerForm->bound($_SESSION['user']);
        }
        $this->page->addVar('registerError', $registerError);
        $this->page->addVar('registerForm', $registerForm);
    }
    
    public function executeProduitsGagner(HttpRequest $request){
        $user = new User($this->app);
        //on texte si l'utilisateur est bien identifié
        if(!$user->isAuthenticated()){
            $this->app->httpResponse()->redirect('login.html');
        }
        $this->page->addVar('title', 'Mes produits gagnés');
        $manager = $this->managers->getManagerOf('Users');
        $dataList = $manager->getProduitsGagnes($request->app->user()->getId());
        //var_dump($dataList);
        foreach ($dataList as $key => $value) {
            list($dateElt,$heure) = explode(' ', $value['dateFin']);
            $dateElt = explode('-',$dateElt);
            krsort($dateElt);
            $value['dateFin'] = implode('/',$dateElt).'<br/>'._A_.'<br/>'.$heure;
            $value['images'] = array_shift(explode(';',$value['images']));
            $value['net_to_pay'] = (float)($value['prix']*$value['limite']/100)<=(float)$value['enchere']?0:$value['enchere'];
            $dataList[$key] = $value;
        }
        
        $this->page->addVar('dataList', $dataList);
        
    }
    
    public function executeEnchereEnCours(HttpRequest $request){
        $user = new User($this->app);
        //on texte si l'utilisateur est bien identifié
        if(!$user->isAuthenticated()){
            $this->app->httpResponse()->redirect('login.html');
        }
        $this->page->addVar('title', 'Mes enchères en cours');
        $manager = $this->managers->getManagerOf('Users');
        $dataList = $manager->getEncheresEnCours($request->app->user()->getId());
        $this->page->addVar('dataList', $dataList);
        
    }
    
    public function executeMesCredits(HttpRequest $request){
        $user = new User($this->app);
        //on texte si l'utilisateur est bien identifié
        if(!$user->isAuthenticated()){
            $this->app->httpResponse()->redirect('login.html');
        }
        $this->page->addVar('title', 'Mes crédits');
        $manager = $this->managers->getManagerOf('Users');
        $dataList = $manager->getHistoriqueCredits($request->app->user()->getId());
        $this->page->addVar('dataList', $dataList);
        
    }
    //deconnexion d'un users
    public function executeLogout(HttpRequest $request)
    {
        //$user = new $this->app->user();
        //if($user->isAuthenticated()){
        if($_SESSION['auth']){
            unset ($_SESSION['auth']);
            unset ($_SESSION['user']);
            unset ($_SESSION['admin']);
            $this->app->httpResponse()->redirect('/');
        }
    }
    
    public function logIn(array $user)
    {
       
        foreach ($user as $key => $value)
        {
            
            $_SESSION['user']['id'] = $value->getId();
            $_SESSION['user']['pseudo'] = $value->getPseudo();
            $_SESSION['user']['email'] = $value->getEmail();
            $_SESSION['user']['password'] = $value->getPassword();
            $_SESSION['user']['nom'] = $value->getNom();
            $_SESSION['user']['prenom'] = $value->getPrenom();
            $_SESSION['user']['ville'] = $value->getVille();
            $_SESSION['user']['adresse'] = $value->getAdresse();
            $_SESSION['user']['cp'] = $value->getCp();
            $_SESSION['user']['pays'] = $value->getPays();
            $_SESSION['user']['fixe'] = $value->getFixe();
            $_SESSION['user']['portable'] = $value->getPortable();
            $_SESSION['user']['credits'] = $value->getCredits();
            $_SESSION['user']['news'] = $value->getNews();
            $_SESSION['user']['conditions'] = $value->getConditions();
            $_SESSION['user']['civilite'] = $value->getCivilite();
            $_SESSION['user']['ip'] = $value->getIp();
            $_SESSION['user']['role'] = $value->getRole();
            
        }
        $_SESSION['auth'] = true;
    }
    
    public function sendMail($email, $pseudo) {
	
		mail($email, 'Votre inscription sur ' . __SITE__ . '',
		'<html>
		 <body>
		 Récapitulatif de vos informations :<br /><br />
		 
		 ' . $pseudo . '<br />
		 ' . $email . '<br /><br />
		 
		 Votre mot de passe est tenu secret. Si vous souhaitez le modifier, rendez-vous sur la page &laquo; Mot de passe perdu? &raquo;<br /><br />

		 L\'équipe de ' . __SITE__ . '
		 </body>
		 </html>', 'From: "' . __SITE__ . '"<' . __EMAIL__ . '>\n
					Content-Type: text/html; charset="iso-8859-1"\n');
	
	}
    
}

?>
